package com.java.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.java.model.Courier;
import com.java.model.PageBean;
import com.java.service.CourierService;
import com.java.util.AppConfig;
import com.java.util.PageUtil;
import com.java.util.ResponseUtil;
import com.java.util.StringUtil;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("/courier")
public class CourierController {

	@Autowired
	private CourierService courierService;

	@RequestMapping("/list")
	public ModelAndView list(@RequestParam(value = "page", required = false) String page, Courier s_courier,
			HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		HttpSession session = request.getSession();
		System.out.println(page);
		if (StringUtil.isEmpty(page)) {
			page = "1";
			session.setAttribute("s_courier", s_courier);
			System.out.println(s_courier.getId());
		} else {
			s_courier = (Courier) session.getAttribute("s_courier");
		}
		PageBean pageBean = new PageBean(Integer.parseInt(page), AppConfig.pageSize);
		List<Courier> courierList = courierService.find(pageBean, s_courier);
		int total = courierService.count(s_courier);
		String pageCode = PageUtil.getPagation(request.getContextPath() + "/courier/list.do", total,
				Integer.parseInt(page), AppConfig.pageSize);
		mav.addObject("pageCode", pageCode);
		mav.addObject("modeName", "快递员(寄快递)");
		mav.addObject("courierList", courierList);
		mav.addObject("mainPage", "courier/list.jsp");
		mav.setViewName("main");
		return mav;
	}

	@RequestMapping("/preSave")
	public ModelAndView preSave(@RequestParam(value = "id", required = false) String id) {
		ModelAndView mav = new ModelAndView();
		mav.addObject("mainPage", "courier/save.jsp");
		mav.addObject("modeName", "快递公司管理");
		mav.setViewName("main");
		if (StringUtil.isNotEmpty(id)) {
			mav.addObject("actionName", "快递公司修改");
			Courier courier = courierService.loadById(Integer.parseInt(id));
			mav.addObject("courier", courier);
		} else {
			mav.addObject("actionName", "快递公司添加");
		}
		return mav;
	}

	@RequestMapping("/save")
	public String save(Courier courier) {
		if (courier.getId() == null) {
			courierService.add(courier);
		} else {
			courierService.update(courier);
		}
		return "redirect:/courier/list.do";
	}

	@RequestMapping("/delete")
	public void delete(@RequestParam(value = "id") String id, HttpServletResponse response) throws Exception {
		JSONObject result = new JSONObject();
		courierService.delete(Integer.parseInt(id));
		result.put("success", true);
		ResponseUtil.write(result, response);
	}
}
